package com.syqc.monitor.ui.alarm

import android.text.Html
import android.view.WindowManager
import androidx.activity.viewModels
import androidx.recyclerview.widget.GridLayoutManager
import autodispose2.autoDispose
import com.syqc.base.BaseReportViewModel
import com.syqc.base.BaseSureActivity
import com.syqc.choose.car.ChooseCarActivity
import com.syqc.choose.teamcar.TeamsCarsActivity
import com.syqc.comlib.custom.timer.CustomDatePicker
import com.syqc.comlib.custom.timer.DateFormatUtils
import com.syqc.comlib.rx.doAfterChanged
import com.syqc.comlib.rx.filterFast
import com.syqc.comlib.utils.ActivityResultUtil.launchAct
import com.syqc.comlib.utils.ActivityResultUtil.registerResultOk
import com.syqc.comlib.utils.ToolbarHelper
import com.syqc.comlib.utils.startActivityTo
import com.syqc.monitor.R
import com.syqc.monitor.databinding.ActivityAlarmNormalBinding
import com.syqc.monitor.databinding.IncludeChooseCarTimeBinding
import com.syqc.monitor.databinding.IncludeChooseFastTimeBinding
import com.syqc.monitor.databinding.IncludeRecyclerWrapBinding
import com.syqc.monitor.ui.realalarm.AlarmChooseActivity2
import com.syqc.adapter.ChooseTimeAdapter
import com.syqc.utils.DataUtil
import com.syqc.utils.Keys
import com.syqc.utils.NetDataUtil
import com.syqc.utils.TimeUtil
import com.syqc.utils.ToolsUtil

/**
 *@Author Jasper
 *@Time   2020/12/9
 *@Desc   报警查询
 */
abstract class BaseAlarmActivity :
    BaseSureActivity<ActivityAlarmNormalBinding>(ActivityAlarmNormalBinding::inflate) {
    abstract val isAdas: Boolean
    val mViewModel by viewModels<BaseAlarmViewModel>()

    val mBaseViewModel: BaseReportViewModel
        get() = mViewModel

    val titleId: Int
        get() = if (isAdas) R.string.title_report_adas else R.string.title_report_alarm

    private lateinit var mReportVB: IncludeChooseFastTimeBinding
    private lateinit var mRecyclerVB: IncludeRecyclerWrapBinding
    lateinit var mChooseVB: IncludeChooseCarTimeBinding


    private fun initIntent() {
        val carId = intent.getStringExtra(Keys.INTENT_CAR_ID)
        val carName = intent.getStringExtra(Keys.INTENT_PLATE) ?: ""
        if (carId == null) return
        mBaseViewModel.carId = carId
        mBaseViewModel.carName = carName
        mChooseVB.lrvChooseCar.setRightText(carName)
        mChooseVB.lrvChooseCar.isEnabled = false
    }


    override fun initView() {
        super.initView()
        window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN)
        mReportVB = IncludeChooseFastTimeBinding.bind(binding.root)
        mRecyclerVB = IncludeRecyclerWrapBinding.bind(binding.root)
        mChooseVB = IncludeChooseCarTimeBinding.bind(binding.root)
        if (titleId != 0) {
            ToolbarHelper.setToolbar(this, titleId)
        }
        mBaseViewModel.toastObserver().autoDispose(scopeProvider).subscribe(this::toastObserver)

        mRecyclerVB.recyclerWrap.layoutManager = GridLayoutManager(this, 4)
        mRecyclerVB.recyclerWrap.adapter = mTimeAdapter.apply {
            setNewInstance(mBaseViewModel.timeList)
            setOnItemClickListener { _, _, position ->
                index = position
                notifyDataSetChanged()
                mBaseViewModel.chooseTime(position)
            }
        }

        mBaseViewModel.startObserve().autoDispose(scopeProvider).subscribe {
            mChooseVB.lrvStartTime.setRightText(it)
        }

        mBaseViewModel.endObserve().autoDispose(scopeProvider).subscribe {
            mChooseVB.lrvEndTime.setRightText(it)
        }

        initIntent()
        initViewModel()
    }

    private fun initViewModel() {
        mViewModel.toastObserver().autoDispose(scopeProvider).subscribe(::toastObserver)
        mViewModel.dataObserver().autoDispose(scopeProvider).subscribe {
            if (isAdas) {
                startActivityTo<AdasInfoActivity>(this) {
                    putExtra(Keys.INTENT_TITLE, mViewModel.carName)
                    putExtra(Keys.INTENT_CAR_ID, mViewModel.carId)
                    putExtra(Keys.INTENT_DATA, it)
                    DataUtil.alarmEntity = it
                }
            } else {
                startActivityTo<NormalInfoActivity>(this) {
                    putExtra(Keys.INTENT_TITLE, mViewModel.carName)
                    putExtra(Keys.INTENT_CAR_ID, mViewModel.carId)
                    putExtra(Keys.INTENT_START_TIME, "${mChooseVB.lrvStartTime.getRightText()}:00")
                    putExtra(Keys.INTENT_END_TIME, "${mChooseVB.lrvEndTime.getRightText()}:59")
                    DataUtil.alarmEntity = it
                }
            }
        }
//        mViewModel.typeIds =     NetDataUtil.getDefaultIds(isAdas)
//        binding.lrTvAlarmType.setRightText(
//            Html.fromHtml(mViewModel.getHtml(getString(R.string.desc_selected),isAdas))
//        )
    }

    override fun setListener() {
        mChooseVB.lrvChooseCar.rightClick {
            if (NetDataUtil.isSyncTree) {
                carLauncher.launchAct<TeamsCarsActivity>(this)
            } else {
                carLauncher.launchAct<ChooseCarActivity>(this)
            }
        }

        mChooseVB.lrvStartTime.rightClick {
            mBaseViewModel.isStart = true
            mDatePicker.show(mChooseVB.lrvStartTime.getRightText())
        }

        mChooseVB.lrvEndTime.rightClick {
            mBaseViewModel.isStart = false
            mDatePicker.show(mChooseVB.lrvEndTime.getRightText())
        }

        mSureVB.tvSure.filterFast {
            if (ToolsUtil.isFastClick()) return@filterFast
            val startTime = mChooseVB.lrvStartTime.getRightText()
            val endTime = mChooseVB.lrvEndTime.getRightText()
            mBaseViewModel.isParamOk(startTime, endTime)
            if (mViewModel.carId.isNotEmpty() && mViewModel.typeIds.isNotEmpty()) saveSet()
        }

        binding.editAlarmRunSpeed.doAfterChanged {
            mViewModel.runSpeed = it
        }

        binding.editAlarmContinue.doAfterChanged {
            mViewModel.duration = it
        }

        binding.lrTvAlarmType.filterFast {

            alarmLauncher.launchAct<AlarmChooseActivity2>(this) {
                putExtra(Keys.INTENT_OTHER, isAdas)
                putExtra(Keys.INTENT_DATA, mViewModel.typeIds)
            }
        }
    }

    private val carLauncher = registerResultOk { result ->
        result.data?.let {
            val carId = it.getStringExtra(Keys.INTENT_CAR_ID) ?: ""
            val carName = it.getStringExtra(Keys.INTENT_CAR_NAME) ?: ""
//                val videos = it.getStringExtra(Keys.VIDEO)
            mChooseVB.lrvChooseCar.setRightText(carName)
            mBaseViewModel.carName = carName
            mBaseViewModel.carId = carId
        }
    }
    private val alarmLauncher = registerResultOk { result ->
        result.data?.let {
            val typeIds = it.getStringExtra("alarmIds") ?: ""
            mViewModel.typeIds = typeIds
            binding.lrTvAlarmType.setRightText(
                Html.fromHtml(mViewModel.getHtml(getString(R.string.desc_selected), isAdas))
            )
        }
    }

    //////////////////////////////////////时间选择///////////////////////////////////////////////
    private val mTimeAdapter: ChooseTimeAdapter by lazy { ChooseTimeAdapter() }

    private val mDatePicker: CustomDatePicker by lazy {
        CustomDatePicker(
            this,
            callback,
            TimeUtil.normalDate,
            mBaseViewModel.nowTimeFormat(),
            !mBaseViewModel.isSimple
        ).apply {
            setCanShowPreciseTime(!mBaseViewModel.isSimple)
        }
    }


    private val callback: CustomDatePicker.Callback = object : CustomDatePicker.Callback {
        override fun onTimeSelected(timestamp: Long) {
            mTimeAdapter.index = -1
            mTimeAdapter.notifyDataSetChanged()
            val time: String = DateFormatUtils.long2Str(timestamp, !mBaseViewModel.isSimple)

            if (mBaseViewModel.isStart) {
//                if (mBaseViewModel.isOkStart(time, mChooseVB.lrvEndTime.getRightText())) return
                mChooseVB.lrvStartTime.setRightText(time)
            } else {
//                if (mBaseViewModel.isTimeOk(mChooseVB.lrvStartTime.getRightText(), time)) return
                mChooseVB.lrvEndTime.setRightText(time)
            }
            mDatePicker.dismiss()
        }
    }

    abstract fun saveSet()

}